package com.easydisk.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easydisk.user.config.RedisServer;
import com.easydisk.user.dao.RoleMapper;
import com.easydisk.user.dao.UserAndRoleMapper;
import com.easydisk.user.dao.UserMapper;
import com.easydisk.user.model.entity.Role;
import com.easydisk.user.model.entity.User;
import com.easydisk.user.model.entity.UserAndRole;
import com.easydisk.user.pojo.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private RedisServer redisServer;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //通过账号查询用户信息
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",s);
        User user = userMapper.selectOne(queryWrapper);
        //BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //System.out.println(user.toString());
        //user.setPassword(encoder.encode(user.getPassword()));
        //获取用户权限列表
        QueryWrapper<UserAndRole> userAndRole=new QueryWrapper<>();
        QueryWrapper<Role> wrapper=new QueryWrapper<>();
        userAndRole.eq("user_id",user.getId());
        List<String> roleList=userAndRoleMapper.selectList(userAndRole)
                .stream().map(roleId ->(roleMapper.selectById(roleId.getRoleId()).getRoleName())).collect(Collectors.toList());
        //存放用户信息到redis中
        String userid=user.getId().toString();
        redisServer.setCache(userid,user);
        //存放用户权限到redis中
        String user_role=userid+"-role";
        redisServer.rightPushAll(user_role,roleList);
        //封装数据到userdetails中
        LoginUser loginUser=new LoginUser();
        com.easydisk.entity.User user1 = new com.easydisk.entity.User();
        BeanUtils.copyProperties(user, user1);
        loginUser.setUser(user1);
        loginUser.setListRole(roleList);
        return loginUser;
    }


}
